package controller.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import entity.file.FileName;
import entity.file.MyFile;
import service.file.IFileService;

@Controller
@RequestMapping("/file")
public class FileController {

	@Resource
	private IFileService fileServiceImpl;

	/**
	 * 上传文件
	 * 
	 * @param request
	 * @param out
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/uploadFile")
	public void uploadFile(HttpServletRequest request, PrintWriter out) {
		JSONObject data = new JSONObject();
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null) {
					String md5Vaule = request.getParameter("md5Vaule");
					String myFileName = file.getOriginalFilename();
					if (myFileName.trim() != "") {
						System.out.println(myFileName);
						// 重命名上传后的文件名(由具体业务决定)
						String fileName = System.currentTimeMillis() + myFileName;
						// 定义上传路径(由具体业务决定)
						String path = "F:/" + fileName;
						try {
							MyFile myFile = fileServiceImpl.saveFile(file, path, md5Vaule);
							data.put("fileId", myFile.getId());
						} catch (Exception e) {
							File errorFile = new File(path);
							errorFile.deleteOnExit();
							data.put("fileId", false);
							e.printStackTrace();
						}
					}
				}
			}
		}
		out.write(data.toJSONString());
	}

	/**
	 * 验证文件是否支持秒传
	 * 
	 * @param request
	 * @param out
	 * @param md5value
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/isSupportSecondUpload")
	public void isSupportSecondUpload(HttpServletRequest request, PrintWriter out, String md5Value, double size,
			String type) {
		JSONObject data = new JSONObject();
		try {
			MyFile myFile = fileServiceImpl.getFileByMd5Value(md5Value, size, type);
			if (myFile != null) {
				data.put("id", myFile.getId());
			} else {
				data.put("id", false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}

	/**
	 * 下载文件
	 * 
	 * @param request
	 * @param out
	 * @param id
	 */
	@RequestMapping("/downloadFile")
	public void downloadFile(HttpServletRequest request, HttpServletResponse resp, String id) {
		try {
			FileName fileName = fileServiceImpl.getFileNameById(id);
			if (fileName != null) {
				MyFile myFile = fileName.getMyFile();
				if (myFile != null) {
					File file = new File(myFile.getPath());
					if (!file.exists()) {
						resp.sendError(HttpServletResponse.SC_NOT_FOUND);
						return;
					}
					resp.setContentType(myFile.getType() + "; charset=UTF-8");
					resp.setHeader("Content-Disposition",
							"attachment;filename=" + new String((fileName.getName()).getBytes("GBK"), "ISO-8859-1"));
					InputStream stream = null;
					OutputStream os = null;
					try {
						stream = new FileInputStream(file);
						os = resp.getOutputStream();
						int readBytes = 0;
						byte buffer[] = new byte[10240];
						while ((readBytes = stream.read(buffer, 0, 10240)) != -1) {
							os.write(buffer, 0, readBytes);
						}
						os.flush();
						os.close();
						stream.close();
					} catch (Exception ex) {
						if (os != null)
							os.close();
						if (stream != null)
							stream.close();
						throw ex;
					} finally {
						if (os != null)
							os.close();
						if (stream != null)
							stream.close();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
